package com.ruoyi.web.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.SysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/sns")
public class SnsLoginController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysLoginService loginService;

    /**
     * 第一步，获取授权码（code）
     *
     * @param platformName
     * @param response
     * @throws Exception
     */
    @GetMapping("/authorize/{platformName}")
    public void authorize(@PathVariable String platformName, HttpServletResponse response) throws Exception {
        response.sendRedirect("https://gitee.com/oauth/authorize?client_id=031733fff1e1cfa39aa15f418d30cd256af603522c9ebb0d927b12924d7152b9&redirect_uri=http://localhost:81/login&response_type=code");
    }

    /**
     * 获取授权码成功后，第三方应用自动回调前端页面（在第三方应用中配置的回调地址）
     * 前端页面根据授权码调用/{platformName}/snsLogin控制器
     * /{platformName}/snsLogin控制器根据授权码获取accessToken
     * 根据accessToken获取用户信息
     * 根据用户信息创建token返回给前端
     * 前端在异步回调方法中获取token后设置登录成功并路由
     */
    @GetMapping("/{platformName}/snsLogin")
    public AjaxResult snsLogin(@PathVariable String platformName, String code) {
        System.out.println("code = " + code);
        // 2、根据授权码获取access_token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&code=" + code +
                "&client_id=031733fff1e1cfa39aa15f418d30cd256af603522c9ebb0d927b12924d7152b9" +
                "&redirect_uri=http://localhost:81/login" +
                "&client_secret=46b577c2b5f7668fac0c7100e114896ee86b17889ea8822c43578bbf1037ec62";
        Map map = restTemplate.postForObject(url, null, Map.class);
        System.out.println("map = " + map);
        String accessToken = (String) map.get("access_token");
        // 3、根据access_token获取账号信息
        String userInfoUrl = "https://gitee.com/api/v5/user?access_token=" + accessToken;
        Map userInfo = restTemplate.getForObject(userInfoUrl, Map.class);
        System.out.println("userInfo = " + userInfo);
        String loginName = platformName + "_" + userInfo.get("login");
        String nickName = (String) userInfo.get("name");
        // 4、进行本系统登录流程
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.snsLogin(loginName, nickName);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}
